package ServletDemo2;//package ServletDemo01;

import util.GokJDBCUtil;
import entity.Admin;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class StudentEditServlet
 */
@WebServlet("/ReaderEdit")
public class ReaderEdit extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReaderEdit() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		Admin reader = GokJDBCUtil.queryForObject("SELECT * FROM admin WHERE id=?", Admin.class, id);

		// 将读者数据设置为请求属性，供表单使用
		request.setAttribute("reader", reader);

		// 转发到编辑页面
		request.getRequestDispatcher("reader-edit.jsp").forward(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String pd = request.getParameter("pd");

		// 更新数据库中的读者数据
		int result = GokJDBCUtil.update("UPDATE admin SET name=?, pd=? WHERE id=?", name, pd, id);

		// 如果更新成功，重定向到读者列表页面
		if (result > 0) {
			response.sendRedirect("ReaderList");
		} else {
			// 如果更新失败，显示错误消息并返回编辑页面
			request.setAttribute("error", "更新失败，请重试！");
			request.getRequestDispatcher("reader-edit.jsp").forward(request, response);
		}
	}
}